﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;


namespace EasyTrader.Form
{
    using DataItemList = List<EasyTrader.DataSet.BarDataItem>;
    using CodeList = List<EasyTrader.DataSet.CodeTable>;
    using BarTableList = List<EasyTrader.DataSet.BarDataTable>;
    using DDEDataList = List<EasyTrader.Option.DDEData>;
    using SimpleDataList = List<EasyTrader.DataSet.SimpleData>;
    public partial class OptionSystemFrm : System.Windows.Forms.Form
    {
        private DDEDataList m_DDEValList = new DDEDataList();
        private SimpleDataList m_CrossValList = new SimpleDataList();

        private string m_CallCode = "";
        private string m_PutCode = "";
        private BarTableList m_ChartTableList = new BarTableList();
        //private List<string> m_SeriesNameList = new List<string>();

        // 차트 데이터 목록에서 중심으로 사용하는 인덱스이다.
        // 이 중심 인덱스를 중심으로 위아래 행사가의 개수가 차트에 나타 난다.
        private int m_CenterIndex = 1;
        public int CenterIndex
        {
            get { return m_CenterIndex; }
            set { m_CenterIndex = value; }
        }

        // 차트 중심 인덱스를 중심으로 행사가를 위아래로 몇개씩 포함시킬 것인지 정한다.
        // 0일 경우는 중심 행사가만을 포함하게 된다.
        private int m_IndexRange = 0;
        public int IndexRange
        {
            get { return m_IndexRange; }
            set { m_IndexRange = value; }
        }
        public OptionSystemFrm()
        {
            InitializeComponent();
        }

        int curChartType = 0;
        // Cybos Plus Data Set Member
        private EasyTrader.ETDataSet m_OpDataSet = null;
        public EasyTrader.ETDataSet OpDataSet
        {
            get { return m_OpDataSet; }
            set { m_OpDataSet = value; }
        }


        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private void InitTimer()
        {
            timer.Interval = GlobalVar.ChartRefreshInterval;
            timer.Tick += new EventHandler(OnTimerTick);
            timer.Start();
        }

        // 여기서 차트를 갱신해 준다.
        private void OnTimerTick(object sender, EventArgs e)
        {
            // 차트에 데이터를 대응시켜 준다.
            SetChartData();
        }

        private void DrawOpVal(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                if (area.Name == "Price")
                {
                    double highXValue = 0;
                    double highYValue = 0;

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Regular);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                    string valueText = "";
                    if (GlobalVar.OPNVAL.BreakCode != "")
                    {
                        string sideCode = GlobalVar.OPNVAL.BreakCode.Substring(0, 1);
                        string priceCode = GlobalVar.OPNVAL.BreakCode.Substring(GlobalVar.OPNVAL.BreakCode.Length - 3, 3);
                        if (sideCode == "2")
                        {
                            valueText += "콜 : " + priceCode + "\n";
                        }
                        else
                        {
                            valueText += "풋 : " + priceCode + "\n";
                        }
                    }
                    valueText += "가격 : " + GlobalVar.OPNVAL.Val.ToString("F2") + "\n";
                    valueText += "현재가 : " + GlobalVar.OPNVAL.CurVal.ToString("F2") + "\n";
                    valueText += "차이 : " + GlobalVar.OPNVAL.DeltaY.ToString("F2") + "\n";
                    if (GlobalVar.OPNVAL.Type == 0)
                    {
                        valueText += "종류 : " + "월저가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 1)
                    {
                        valueText += "종류 : " + "마디가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 2)
                    {
                        valueText += "종류 : " + "기준가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 3)
                    {
                        valueText += "종류 : " + "목표가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 4)
                    {
                        valueText += "종류 : " + "월고가";
                    }

                    highXValue = GlobalVar.OPNVAL.Index;
                    highYValue = GlobalVar.OPNVAL.Y;

                    // Convert X and Y values to screen position
                    float pixelYMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                    float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);

                    // Specify width of triangle
                    float width = 1;

                    // Set Maximum points
                    PointF[] points = new PointF[3];
                    points[0].X = pixelXMax;
                    points[0].Y = pixelYMax;
                    points[1].X = pixelXMax - width;
                    points[1].Y = pixelYMax - 2;
                    points[2].X = pixelXMax - width;
                    points[2].Y = pixelYMax + 2;

                    // Convert relative coordinates to absolute coordinates.
                    points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                    points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                    points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                    DateTime date = DateTime.Now;
                    if (Math.Abs(GlobalVar.OPNVAL.DeltaY) < 0.2)
                    {
                        int mod = date.Second % 2;
                        if (mod == 0)
                        {
                            graphics.FillPolygon(new SolidBrush(Color.Blue), points);
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[0].X - 100, points[0].Y - 35);
                        }
                        else
                        {
                            graphics.FillPolygon(new SolidBrush(Color.Red), points);
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[0].X - 100, points[0].Y - 35);
                        }


                    }
                    else
                    {
                        graphics.FillPolygon(new SolidBrush(Color.Magenta), points);
                        // Draw the string.
                        graphics.DrawString(valueText, myFont,
                            Brushes.Magenta, points[0].X - 100, points[0].Y - 35);
                    }
                }
            }
        }


        private void MakeDataTableList()
        {
            m_ChartTableList.Clear();
            int listCount = m_OpDataSet.OptChartTableList.Count;
            // 여기서 중심 인덱스를 찾아서 설정해 준다.

            int startIndex = m_CenterIndex - m_IndexRange;
            if (startIndex < 0)
                startIndex = 0;
            int endIndex = m_CenterIndex + m_IndexRange;
            if (endIndex > listCount - 1)
                endIndex = listCount - 1;
            // 콜 테이블 추가
            for (int i = startIndex; i <= endIndex; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_OpDataSet.OptChartTableList[i];
                m_ChartTableList.Add(table);
            }

            int index = m_CenterIndex + (int)(listCount / 2.0);
            startIndex = index - m_IndexRange;
            if (startIndex < 0)
                startIndex = 0;
            endIndex = index + m_IndexRange;
            if (endIndex > listCount - 1)
                endIndex = listCount - 1;
            // 풋 테이블 추가
            for (int i = startIndex; i <= endIndex; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_OpDataSet.OptChartTableList[i];
                m_ChartTableList.Add(table);
            }
        }

        private void MakeDDEValList()
        {
            m_DDEValList.Clear();
            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    EasyTrader.Option.DDEData curDDE = m_OpDataSet.FindDDEData(m_OpDataSet.DownLoader.CurDay, table.TableName);
                    if (curDDE != null)
                    {
                        m_DDEValList.Add(curDDE);
                    }
                }
            }
        }

        private SimpleDataList m_TempList = new SimpleDataList();
        private void MakeCrossValList()
        {
            m_TempList.Clear();

            // 먼저 중심 목표가와 마디가를 가져 온다.
            m_OpDataSet.FindRecentOptCenterCrossData(m_TempList);
            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    string tableName = table.TableName;
                    string priceCode = tableName.Substring(tableName.Length - 3, 3);
                    m_OpDataSet.FindRecentOptOuterCrossData(m_TempList, priceCode);
                }
            }

            m_CrossValList.Clear();
            for (int i = 0; i < m_TempList.Count; i++)
            {
                EasyTrader.DataSet.SimpleData data = m_TempList[i];
                if (data.CallType != -1)
                {
                    if (IsInSeries(data.CallCode) == true)
                    {
                        if (data.CallType == 0 && m_EnableJoint == true)
                            m_CrossValList.Add(data);
                        if (data.CallType == 1 && m_EnableTarget == true)
                            m_CrossValList.Add(data);
                    }
                }
                if (data.PutType != -1)
                {
                    if (IsInSeries(data.PutCode) == true)
                    {
                        if (data.PutType == 0 && m_EnableJoint == true)
                            m_CrossValList.Add(data);
                        if (data.PutType == 1 && m_EnableTarget == true)
                            m_CrossValList.Add(data);
                    }
                }
            }
        }

        private bool IsInSeries(string a_Code)
        {
            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    if (table.TableName == a_Code)
                        return true;
                }
            }

            return false;
        }

        private void SetMinMaxByDDE()
        {
            double max = -99999;
            double min = 99999;

            for (int i = 0; i < m_DDEValList.Count; i++)
            {
                EasyTrader.Option.DDEData curDDE = m_DDEValList[i];
                if (m_EnableBase == true)
                {
                    if (Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) > max)
                        max = Convert.ToDouble(curDDE.DataItem.CallBase.ToString());
                    if (Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) > min)
                        min = Convert.ToDouble(curDDE.DataItem.CallBase.ToString());
                }

                if (m_EnableMonthLow == true)
                {
                    if (Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) > max)
                        max = Convert.ToDouble(curDDE.DataItem.CallMLow.ToString());
                    if (Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) > min)
                        min = Convert.ToDouble(curDDE.DataItem.CallMLow.ToString());
                }

                if (m_EnableMonthHigh == true)
                {
                    if (Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) > max)
                        max = Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString());
                    if (Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) > min)
                        min = Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString());
                }


                if (m_EnableBase == true)
                {
                    if (Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) > max)
                        max = Convert.ToDouble(curDDE.DataItem.PutBase.ToString());
                    if (Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) > min)
                        min = Convert.ToDouble(curDDE.DataItem.PutBase.ToString());
                }

                if (m_EnableMonthLow == true)
                {
                    if (Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) > max)
                        max = Convert.ToDouble(curDDE.DataItem.PutMLow.ToString());
                    if (Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) > min)
                        min = Convert.ToDouble(curDDE.DataItem.PutMLow.ToString());
                }


                if (m_EnableMonthHigh == true)
                {
                    if (Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) > max)
                        max = Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString());
                    if (Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) > min)
                        min = Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString());
                }
            }

            if (min != 99999 && max != -99999 && max > min)
            {
                FutOptChartCtrl.ChartAreas["Price"].AxisY2.Minimum = min;
                FutOptChartCtrl.ChartAreas["Price"].AxisY2.Maximum = max;
            }
        }

        private void SetMinMaxByCross()
        {
            MakeCrossValList();
            double max = -99999;
            double min = 99999;
            for (int i = 0; i < m_CrossValList.Count; i++)
            {
                EasyTrader.DataSet.SimpleData curData = m_CrossValList[i];
                if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                {
                    if (curData.CallVal != 0.0 && curData.CallVal > max)
                    {
                        if (curData.CallType == 0 && m_EnableJoint == true)
                            max = curData.CallVal;
                        if (curData.CallType == 1 && m_EnableTarget == true)
                            max = curData.CallVal;
                    }
                    if (curData.PutVal != 0.0 && curData.PutVal > max)
                    {
                        if (curData.PutType == 0 && m_EnableJoint == true)
                            max = curData.PutVal;
                        if (curData.PutType == 1 && m_EnableTarget == true)
                            max = curData.PutVal;
                    }
                }

                if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                {
                    if (curData.CallVal != 0.0 && curData.CallVal < min)
                    {
                        if (curData.CallType == 0 && m_EnableJoint == true)
                            min = curData.CallVal;
                        if (curData.CallType == 1 && m_EnableTarget == true)
                            min = curData.CallVal;
                    }
                    if (curData.PutVal != 0.0 && curData.PutVal < min)
                    {
                        if (curData.PutType == 0 && m_EnableJoint == true)
                            min = curData.PutVal;
                        if (curData.PutType == 1 && m_EnableTarget == true)
                            min = curData.PutVal;
                    }
                }
            }
            if (min != 99999 && max != -99999 && max > min)
            {
                FutOptChartCtrl.ChartAreas["Price"].AxisY2.Minimum = min;
                FutOptChartCtrl.ChartAreas["Price"].AxisY2.Maximum = max;
            }
        }

        private void SetChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_OpDataSet == null)
                return;
            m_CenterIndex = m_OpDataSet.FindOptTableIndex(m_CallCode);
            int sCount = FutOptChartCtrl.Series.Count;
            for (int i = 0; i < sCount; i++)
                FutOptChartCtrl.Series[i].Points.Clear();

            if (m_ShowType == 0 || m_ShowType == 1)
                SetFutureChartData(0);
            MakeDataTableList();

            // 여기서부터는 옵션 차트 데이터를 넣어 준다.
            for (int i = 1; i < sCount; i++)
            {
                if (i <= m_ChartTableList.Count)
                {
                    EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i - 1];
                    if (table.GetRowCount() == 0)
                        continue;

                    FutOptChartCtrl.Series[i].Enabled = true;
                    //FutOptChartCtrl.Series[i].Name = table.TableName;
                    string sideCode = table.TableName.Substring(0, 1);
                    if (sideCode == "2")
                    {
                        if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                        {
                            FutOptChartCtrl.Series[i].Color = Color.Red;
                            SetChartData(table, i);
                        }
                        else
                            FutOptChartCtrl.Series[i].Enabled = false;
                    }
                    else
                    {
                        if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                        {
                            FutOptChartCtrl.Series[i].Color = Color.Blue;
                            SetChartData(table, i);
                        }
                        else
                            FutOptChartCtrl.Series[i].Enabled = false;
                    }
                }
                else
                {
                    FutOptChartCtrl.Series[i].Enabled = false;
                }
            }

            SetMinMaxByCross();
            SetMinMaxByDDE();
        }

        private void SetChartData(EasyTrader.DataSet.BarDataTable dataTable, int a_SeriesIndex)
        {
            if (dataTable == null)
                return;

            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;

            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;

            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["고가"] == DBNull.Value)
                        continue;
                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    closeValue = Convert.ToDouble(row["종가"]);
                    string curTime = row["시각"].ToString();
                    string curDate = row["날짜"].ToString();
                    //Console.WriteLine(highValue.ToString("F2"));
                    //Console.WriteLine(lowValue.ToString("F2"));
                    //Console.WriteLine(openValue.ToString("F2"));
                    //Console.WriteLine(closeValue.ToString("F2"));
                    int dayIndex = GlobalVar.DayIndex(curTime, m_OpDataSet.DownLoader.OptChartCycle);
                    if (m_OpDataSet.DownLoader.OptChartUnit == 'M' ||
                            m_OpDataSet.DownLoader.OptChartUnit == 'D')
                    {
                        dayIndex = i;
                    }
                    if (curChartType == 0)
                    {
                        FutOptChartCtrl.Series[a_SeriesIndex].Points.AddXY(dayIndex, highValue);
                        int pCount = FutOptChartCtrl.Series[a_SeriesIndex].Points.Count;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].XValue = dayIndex;
                        if (m_OpDataSet.DownLoader.OptChartUnit == 'M' ||
                            m_OpDataSet.DownLoader.OptChartUnit == 'D')
                        {
                            FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curDate;
                        }
                        else
                            FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curTime;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].YValues[1] = lowValue;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].YValues[2] = openValue;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].YValues[3] = closeValue;
                    }
                    else
                    {
                        FutOptChartCtrl.Series[a_SeriesIndex].Points.AddXY(dayIndex, closeValue);
                        int pCount = FutOptChartCtrl.Series[a_SeriesIndex].Points.Count;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].XValue = dayIndex;
                        if (m_OpDataSet.DownLoader.OptChartUnit == 'M' ||
                            m_OpDataSet.DownLoader.OptChartUnit == 'D')
                        {
                            FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curDate;
                        }
                        else
                            FutOptChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curTime;
                    }

                    m_DataFilled = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }


        private void SetFutureChartData(int a_SeriesIndex)
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_OpDataSet == null)
                return;

            FutOptChartCtrl.Series[a_SeriesIndex].Points.Clear();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_OpDataSet.GetFutOptChartTable();
            double maxValue = -10000.0;
            double minValue = 10000.0;
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;

            int minIndex = 0;
            int maxIndex = 0;
            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;
            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["고가"] == DBNull.Value)
                        continue;
                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    closeValue = Convert.ToDouble(row["종가"]);
                    if (highValue == 0 || lowValue == 0 || openValue == 0 || closeValue == 0)
                        continue;

                    if (curChartType == 0)
                    {
                        FutOptChartCtrl.Series[a_SeriesIndex].Points.AddXY(i, highValue);
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[i].XValue = i;
                        //FutOptChartCtrl.Series[a_SeriesIndex].Points[i].AxisLabel = row["시각"].ToString();
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[i].YValues[1] = lowValue;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[i].YValues[2] = openValue;
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[i].YValues[3] = closeValue;
                    }
                    else
                    {
                        FutOptChartCtrl.Series[a_SeriesIndex].Points.AddXY(i, closeValue);
                        FutOptChartCtrl.Series[a_SeriesIndex].Points[i].XValue = i;
                        //FutOptChartCtrl.Series[a_SeriesIndex].Points[i].AxisLabel = row["시각"].ToString();
                    }

                    if (highValue != 0 && highValue > maxValue)
                    {
                        maxValue = highValue;
                        maxIndex = i;
                    }
                    if (lowValue != 0 && lowValue < minValue)
                    {
                        minValue = lowValue;
                        minIndex = i;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        /*
        private void SetChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_OpDataSet == null)
                return;
            if (m_OpDataSet.PriceDataList.Count == 0)
                return;

            FutOptChartCtrl.Series["지수"].Points.Clear();
            DataItemList dataTable = m_OpDataSet.PriceDataList[m_DataIndex].DataList;
            double maxValue = -10000.0;
            double minValue = 10000.0;
            int rowCount = dataTable.Count;
            int minIndex = 0;
            int maxIndex = 0;
            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;
            for (int i = 0; i < rowCount; i++)
            {
                EasyTrader.Option.OptionDataItem item = dataTable[i];
                try
                {
                    if (Convert.ToDouble(item.Close) == 0.0)
                        break;

                    highValue = Convert.ToDouble(item.High.ToString());
                    lowValue = Convert.ToDouble(item.Low.ToString());
                    openValue = Convert.ToDouble(item.Open.ToString());
                    closeValue = Convert.ToDouble(item.Close.ToString());
                    if (curChartType == 0)
                    {
                        FutOptChartCtrl.Series["지수"].Points.AddXY(i, highValue);
                        FutOptChartCtrl.Series["지수"].Points[i].XValue = i;
                        FutOptChartCtrl.Series["지수"].Points[i].AxisLabel = item.Time.ToString();
                        FutOptChartCtrl.Series["지수"].Points[i].YValues[1] = lowValue;
                        FutOptChartCtrl.Series["지수"].Points[i].YValues[2] = openValue;
                        FutOptChartCtrl.Series["지수"].Points[i].YValues[3] = closeValue;
                    }
                    else
                    {
                        FutOptChartCtrl.Series["지수"].Points.AddXY(i, closeValue);
                        FutOptChartCtrl.Series["지수"].Points[i].XValue = i;
                        FutOptChartCtrl.Series["지수"].Points[i].AxisLabel = item.Time.ToString();
                        //Console.WriteLine(FutOptChartCtrl.Series["지수"].Points.Count.ToString());
                    }

                    if (highValue != 0 && highValue > maxValue)
                    {
                        maxValue = highValue;
                        maxIndex = i;
                    }

                    if (lowValue != 0 && lowValue > maxValue)
                    {
                        maxValue = lowValue;
                        maxIndex = i;
                    }

                    if (openValue != 0 && openValue > maxValue)
                    {
                        maxValue = openValue;
                        maxIndex = i;
                    }

                    if (closeValue != 0 && closeValue > maxValue)
                    {
                        maxValue = closeValue;
                        maxIndex = i;
                    }

                    if (highValue != 0 && highValue < minValue)
                    {
                        minValue = highValue;
                        minIndex = i;
                    }

                    if (lowValue != 0 && lowValue < minValue)
                    {
                        minValue = lowValue;
                        minIndex = i;
                    }

                    if (openValue != 0 && openValue < minValue)
                    {
                        minValue = openValue;
                        minIndex = i;
                    }

                    if (closeValue != 0 && closeValue < minValue)
                    {
                        minValue = closeValue;
                        minIndex = i;
                    }
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            if (maxValue >= minValue)
            {
                FutOptChartCtrl.ChartAreas["Price"].AxisY.Minimum = minValue;
                FutOptChartCtrl.ChartAreas["Price"].AxisY.Maximum = maxValue;
            }

        }
        */

        private bool m_DataFilled = false;
        public OptionSystemFrm(EasyTrader.ETDataSet a_DataSet)
        {
            InitializeComponent();

            m_OpDataSet = a_DataSet;
            m_OpDataSet.CreateDDEData();

            for (int i = 0; i < FutOptChartCtrl.Series.Count; i++)
                FutOptChartCtrl.Series[i].ToolTip = "#VALX : #VAL";

            //tbCurDay.Text = m_OpDataSet.DownLoader.CurDay.ToString();
            comboCycle.SelectedIndex = 0;
            comboFutOptChartType.SelectedIndex = 0;
            rbMin.Checked = true;
            comboShowType.SelectedIndex = 2;
            m_CallCode = GlobalVar.CATM;
            m_PutCode = GlobalVar.PATM;
            cbMonthLow.Checked = true;
            cbBase.Checked = true;
            cbJoint.Checked = true;
            cbMonthHigh.Checked = true;
            cbTarget.Checked = true;
        }

        private void InitChart()
        {
            FutOptChartCtrl.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(211)), ((System.Byte)(223)), ((System.Byte)(240)));
            FutOptChartCtrl.BackSecondaryColor = System.Drawing.Color.White;
            FutOptChartCtrl.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            FutOptChartCtrl.BorderlineColor = System.Drawing.Color.FromArgb(((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            FutOptChartCtrl.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            FutOptChartCtrl.BorderlineWidth = 2;
            FutOptChartCtrl.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;

            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.IsClustered = true;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.Perspective = 10;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.IsRightAngleAxes = false;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.WallWidth = 0;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.Inclination = 15;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.Rotation = 10;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.IsLabelAutoFit = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = false;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisY.IsLabelAutoFit = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            FutOptChartCtrl.ChartAreas["Price"].AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisY.IsStartedFromZero = false;
            //FutOptChartCtrl.ChartAreas["Price"].AxisY2.
            FutOptChartCtrl.ChartAreas["Price"].BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            FutOptChartCtrl.ChartAreas["Price"].BackSecondaryColor = System.Drawing.Color.White;
            FutOptChartCtrl.ChartAreas["Price"].BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            FutOptChartCtrl.ChartAreas["Price"].BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            FutOptChartCtrl.ChartAreas["Price"].Position.Auto = true;
            FutOptChartCtrl.ChartAreas["Price"].ShadowColor = System.Drawing.Color.Transparent;

            FutOptChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.IsMarginVisible = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.IsEndLabelVisible = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.IsMarginVisible = true;
            //CmeDailyChartCtrl.Series[0].Color = Color.Red;
            //DataPointCustomProperties aa = CmeDailyChartCtrl.Series[0]["PriceUpColor"];
        }

        private void FutureOptionChart_Load(object sender, EventArgs e)
        {
            InitChart();
            InitTimer();

            curChartType = 0;
        }

        private void FutureOptionChart_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer.Stop();
        }

        private void comboPriceCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            ;
        }

        private void comboFutOptChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            curChartType = comboFutOptChartType.SelectedIndex;
            if (curChartType != -1)
            {
                if (curChartType == 0)
                {
                    for (int i = 0; i < FutOptChartCtrl.Series.Count; i++)
                        FutOptChartCtrl.Series[i].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                }
                else
                {
                    for (int i = 0; i < FutOptChartCtrl.Series.Count; i++)
                        FutOptChartCtrl.Series[i].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                }
                SetChartData();
                FutOptChartCtrl.Invalidate();
            }
        }


        private void MakeValList(List<double> a_ValList, int a_CodeIndex)
        {
            /*
            a_ValList.Clear();
            EasyTrader.Option.DDEDataCollection ddeCol = m_OpDataSet.FindDDEDataCol(m_OpDataSet.DownLoadManager.CurDay, m_OpDataSet.ChartCodeArray[a_CodeIndex]);

            if (a_CodeIndex > 0 && a_CodeIndex < 4)
            {
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutBase.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutMLow.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutMHigh.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallPreLow.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallPreHigh.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallCurLow.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallCurHigh.ToString()));
            }
            else if (a_CodeIndex >= 4)
            {
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallBase.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallMLow.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallMHigh.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutPreLow.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutPreHigh.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutCurLow.ToString()));
                m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutCurHigh.ToString()));
            }*/
        }

        private List<double> m_CodeValList = new List<double>();

        private void DrawSignal(ChartPaintEventArgs a_EventArg)
        {
            /*
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                int codeIndex = 0;
                if (area.Name == "LeftUp")
                    codeIndex = 1;
                else if (area.Name == "LeftCenter")
                    codeIndex = 2;
                else if (area.Name == "LeftDown")
                    codeIndex = 3;
                else if (area.Name == "RightUp")
                    codeIndex = 4;
                else if (area.Name == "RightCenter")
                    codeIndex = 5;
                else if (area.Name == "RightDown")
                    codeIndex = 6;
                m_CodeValList.Clear();
                EasyTrader.Option.DDEDataCollection ddeCol = m_OpDataSet.FindDDEDataCol(m_OpDataSet.DownLoadManager.CurDay, m_OpDataSet.ChartCodeArray[codeIndex]);

                if (codeIndex > 0 && codeIndex < 4)
                {
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutBase.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutMLow.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutMHigh.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallPreLow.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallPreHigh.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallCurLow.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallCurHigh.ToString()));
                }
                else if (codeIndex >= 4)
                {
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallBase.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallMLow.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.CallMHigh.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutPreLow.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutPreHigh.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutCurLow.ToString()));
                    m_CodeValList.Add(Convert.ToDouble(ddeCol.DataItem.PutCurHigh.ToString()));
                }

                string curCode = m_OpDataSet.ChartCodeList[codeIndex];

                for (int i = 0; i < m_CodeValList.Count; i++)
                {
                    double xMin = 0;
                    double xMax = 0;
                    double YValue = 0;
                    if (m_EnableBase == false && i == 0)
                        continue;
                    if (m_EnableMonthLow == false && i == 1)
                        continue;
                    if (m_EnableMonthHigh == false && i == 2)
                        continue;
                    if (m_EnablePreDayLow == false && i == 3)
                        continue;
                    if (m_EnablePreDayHigh == false && i == 4)
                        continue;

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Regular);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.AntiAlias;
                    string valueText = "";
                    if (i == 0)
                        valueText = "상대기준가";
                    else if (i == 1)
                        valueText = "상대월저가";
                    else if (i == 2)
                        valueText = "상대월고가";
                    else if (i == 3)
                        valueText = "전일저가";
                    else if (i == 4)
                        valueText = "전일고가";
                    else if (i == 5)
                        valueText = "당일저가";
                    else if (i == 6)
                        valueText = "당일고가";

                    xMin = area.AxisX.Minimum;
                    xMax = area.AxisX.Maximum;
                    YValue = m_CodeValList[i];

                    string curValue = String.Format("{0:F2}", YValue);

                    valueText += " : " + curValue;

                    // Convert X and Y values to screen position
                    float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, YValue);
                    float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, area.AxisY.Maximum);
                    float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                    float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);

                    // Set Maximum points
                    PointF[] points = new PointF[3];
                    points[0].X = pixelXMin;
                    points[0].Y = pixelY;

                    points[1].X = pixelXMax;
                    points[1].Y = pixelY;

                    points[2].X = pixelXMin;
                    points[2].Y = pixelMaxY;


                    // Convert relative coordinates to absolute coordinates.
                    points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                    points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                    points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                    //graphics.DrawLine(new Pen(Color.Red, 2), points[0], points[1]);

                    if (i == 0)
                    {
                        graphics.DrawLine(new Pen(Color.Red, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[0].X + 80, points[0].Y);
                    }
                    else if (i == 1)
                    {
                        graphics.DrawLine(new Pen(Color.Blue, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[0].X + 160, points[0].Y);
                    }
                    else if (i == 2)
                    {
                        graphics.DrawLine(new Pen(Color.Orange, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.Orange, points[0].X + 160, points[0].Y);
                    }
                    else if (i == 3)
                    {
                        graphics.DrawLine(new Pen(Color.Brown, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.Brown, points[0].X + 240, points[0].Y);
                    }
                    else if (i == 4)
                    {
                        graphics.DrawLine(new Pen(Color.Purple, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[0].X + 240, points[0].Y);
                    }
                    else if (i == 5)
                    {
                        graphics.DrawLine(new Pen(Color.DarkGreen, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.DarkGreen, points[0].X + 320, points[0].Y);
                    }
                    else if (i == 6)
                    {
                        graphics.DrawLine(new Pen(Color.YellowGreen, 1), points[0], points[1]);
                        graphics.DrawString(valueText, myFont,
                                Brushes.YellowGreen, points[0].X + 320, points[0].Y);
                    }
                    graphics.DrawString(curCode, myFont, Brushes.Magenta, points[2].X, points[2].Y);
                }

            }*/
        }

        private void DrawSeriesName(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                for (int i = 0; i < m_ChartTableList.Count; i++)
                {
                    EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                    if (table.Rows.Count == 0)
                        continue;
                    DataRow row = table.Rows[0];
                    double openValue = Convert.ToDouble(row["시가"]);

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Regular);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.AntiAlias;
                    string valueText = table.TableName;

                    double xMin = area.AxisX.Minimum;
                    double YValue = openValue;

                    // Convert X and Y values to screen position
                    float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, YValue);
                    float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);

                    // Set Maximum points
                    PointF[] points = new PointF[2];
                    points[0].X = pixelXMax - 3.5F;
                    points[0].Y = pixelY;

                    points[1].X = pixelXMax;
                    points[1].Y = pixelY;

                    // Convert relative coordinates to absolute coordinates.
                    points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                    points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);

                    string sideCode = table.TableName.Substring(0, 1);
                    if (sideCode == "2")
                        graphics.DrawString(valueText, myFont, Brushes.Red, points[0].X, points[0].Y);

                    else
                        graphics.DrawString(valueText, myFont, Brushes.Blue, points[0].X, points[0].Y);
                }
            }
        }

        private void DrawCurVal(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                /*
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                int codeIndex = 0;
                if (area.Name == "LeftUp")
                    codeIndex = 1;
                else if (area.Name == "LeftCenter")
                    codeIndex = 2;
                else if (area.Name == "LeftDown")
                    codeIndex = 3;
                else if (area.Name == "RightUp")
                    codeIndex = 4;
                else if (area.Name == "RightCenter")
                    codeIndex = 5;
                else if (area.Name == "RightDown")
                    codeIndex = 6;
                DataItemList dataTable = m_OpDataSet.ChartDataArray[codeIndex].DataList;
                if (dataTable.Count == 0)
                    return;


                double xMax = 0;
                double YValue = 0;

                Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                FontStyle.Regular);

                System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                // Set the TextRenderingHint property.
                graphics.TextRenderingHint =
                    System.Drawing.Text.TextRenderingHint.AntiAlias;
                string valueText = "";

                xMax = area.AxisX.Maximum;
                YValue = Convert.ToDouble(dataTable[dataTable.Count - 1].Close);

                string curValue = String.Format("{0:F2}", YValue);

                valueText = curValue;

                // Convert X and Y values to screen position
                float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, YValue);
                float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);

                // Set Maximum points
                PointF[] points = new PointF[2];
                points[0].X = pixelXMax;
                points[0].Y = pixelY;

                points[1].X = pixelXMax;
                points[1].Y = pixelY;

                // Convert relative coordinates to absolute coordinates.
                points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);

                graphics.DrawString(valueText, myFont, Brushes.Red, points[0].X, points[0].Y);
                 */
            }
        }

        private void DrawConstPrice(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                for (int i = 0; i < GlobalVar.m_OpConstPriceList.Length; i++)
                {
                    double xMin = 0;
                    double xMax = 0;
                    double YValue = 0;
                    double YMin = 0.0;
                    double YMax = 0.0;
                    if (m_EnableBase == false && i == 0)
                        continue;
                    if (m_EnableMonthLow == false && i == 1)
                        continue;
                    if (m_EnableMonthHigh == false && i == 2)
                        continue;
                    if (m_EnablePreDayLow == false && i == 3)
                        continue;
                    if (m_EnablePreDayHigh == false && i == 4)
                        continue;

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Regular);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.AntiAlias;
                    string valueText = "중요가격";


                    xMin = area.AxisX.Minimum;
                    xMax = area.AxisX.Maximum;
                    YMin = area.AxisY.Minimum;
                    YMax = area.AxisY.Maximum;
                    YValue = GlobalVar.m_OpConstPriceList[i];

                    if (YValue > YMax || YValue < YMin)
                        continue;

                    string curValue = String.Format("{0:F2}", YValue);

                    valueText += " : " + curValue;

                    // Convert X and Y values to screen position
                    float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, YValue);
                    float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, area.AxisY.Maximum);
                    float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                    float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);

                    // Set Maximum points
                    PointF[] points = new PointF[3];
                    points[0].X = pixelXMin;
                    points[0].Y = pixelY;

                    points[1].X = pixelXMax;
                    points[1].Y = pixelY;

                    points[2].X = pixelXMin;
                    points[2].Y = pixelMaxY;


                    // Convert relative coordinates to absolute coordinates.
                    points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                    points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                    points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                    graphics.DrawLine(new Pen(Color.DarkOrange, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.DarkOrange, points[0].X + 400, points[0].Y);
                }

            }
        }


        private void DrawDDEPrice(ChartPaintEventArgs a_EventArg)
        {
            MakeDDEValList();

            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                for (int i = 0; i < m_DDEValList.Count; i++)
                {
                    EasyTrader.Option.DDEData curDDE = m_DDEValList[i];
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                    {
                        DrawDDEVal(a_EventArg, 0, Convert.ToDouble(curDDE.DataItem.PutBase), curDDE.CallCode.ToString());
                        DrawDDEVal(a_EventArg, 1, Convert.ToDouble(curDDE.DataItem.PutMLow), curDDE.CallCode.ToString());
                        DrawDDEVal(a_EventArg, 2, Convert.ToDouble(curDDE.DataItem.PutMHigh), curDDE.CallCode.ToString());
                    }
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                    {
                        DrawDDEVal(a_EventArg, 0, Convert.ToDouble(curDDE.DataItem.CallBase), curDDE.PutCode.ToString());
                        DrawDDEVal(a_EventArg, 1, Convert.ToDouble(curDDE.DataItem.CallMLow), curDDE.PutCode.ToString());
                        DrawDDEVal(a_EventArg, 2, Convert.ToDouble(curDDE.DataItem.CallMHigh), curDDE.PutCode.ToString());
                    }
                }

            }

            //FutOptChartCtrl.Invalidate(false);
        }

        private void DrawCrossPrice(ChartPaintEventArgs a_EventArg)
        {
            MakeCrossValList();
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                for (int i = 0; i < m_CrossValList.Count; i++)
                {
                    EasyTrader.DataSet.SimpleData curDDE = m_CrossValList[i];
                    //DrawCrossVal(a_EventArg, curDDE.Type, curDDE.Val, curDDE.Code, curDDE.CenterVal);
                    // 콜
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                    {
                        DrawCrossVal(a_EventArg, curDDE.PutType, curDDE.PutVal, curDDE.CallCode, curDDE.CenterVal);
                    }
                    // 풋
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                    {
                        DrawCrossVal(a_EventArg, curDDE.CallType, curDDE.CallVal, curDDE.PutCode, curDDE.CenterVal);
                    }
                }

            }

            //FutOptChartCtrl.Invalidate(false);
        }

        private void DrawCrossVal(ChartPaintEventArgs a_EventArg, int a_Type, double a_Val, string a_Code, string a_CenterVal)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                double xMin = 0.0;
                double xMax = 0.0;
                double YValue = 0.0;
                double YMin = 0.0;
                double YMax = 0.0;
                string sideCode = a_Code.Substring(0, 1);
                string priceCode = a_Code.Substring(a_Code.Length - 3, 3);

                string valueText = "";
                if (sideCode == "2")
                    valueText += "콜" + priceCode + " : ";
                else
                    valueText += "풋" + priceCode + " : ";

                if (a_Type == 0)
                {
                    if (priceCode == a_CenterVal)
                        valueText += "상대중심마디가";
                    else
                        valueText += "상대마디가";
                }
                else if (a_Type == 1)
                {
                    if (priceCode == a_CenterVal)
                        valueText += "상대중심목표가";
                    else
                        valueText += "상대목표가";
                }


                if (a_Type == 0 && m_EnableJoint == false)
                    return;
                if (a_Type == 1 && m_EnableTarget == false)
                    return;


                Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                FontStyle.Regular);

                System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                // Set the TextRenderingHint property.
                graphics.TextRenderingHint =
                    System.Drawing.Text.TextRenderingHint.AntiAlias;


                xMin = area.AxisX.Minimum;
                xMax = area.AxisX.Maximum;
                YMin = area.AxisY2.Minimum;
                YMax = area.AxisY2.Maximum;
                YValue = a_Val;

                if (YValue > YMax || YValue < YMin)
                    return;

                string curValue = String.Format("{0:F2}", YValue);

                valueText += " : " + curValue;

                // Convert X and Y values to screen position
                float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, YValue);
                float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, area.AxisY2.Maximum);
                float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);

                // Set Maximum points
                PointF[] points = new PointF[3];
                points[0].X = pixelXMin;
                points[0].Y = pixelY;

                points[1].X = pixelXMax;
                points[1].Y = pixelY;

                points[2].X = pixelXMin;
                points[2].Y = pixelMaxY;


                // Convert relative coordinates to absolute coordinates.
                points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                if (sideCode == "2")
                {
                    graphics.DrawLine(new Pen(Color.Red, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Magenta, points[0].X + 150, points[0].Y);
                }
                else
                {
                    graphics.DrawLine(new Pen(Color.Blue, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Green, points[0].X + 150, points[0].Y);
                }

            }
        }

        // ddde val type : 0 : 기준가, 1 : 월저가, 2 : 월고가, 3 : 마디가, 4 : 목표가, 5 : 교차가
        private void DrawDDEVal(ChartPaintEventArgs a_EventArg, int a_Type, double a_Val, string a_Code)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                double xMin = 0.0;
                double xMax = 0.0;
                double YValue = 0.0;
                double YMin = 0.0;
                double YMax = 0.0;
                string sideCode = a_Code.Substring(0, 1);
                string priceCode = a_Code.Substring(a_Code.Length - 3, 3);

                string valueText = "";
                if (sideCode == "2")
                    valueText += "콜" + priceCode + " : ";
                else
                    valueText += "풋" + priceCode + " : ";

                if (a_Type == 0)
                    valueText += "상대기준가";
                else if (a_Type == 1)
                    valueText += "상대월저가";
                else if (a_Type == 2)
                    valueText += "상대월고가";
                else if (a_Type == 3)
                    valueText += "상대마디가";
                else if (a_Type == 4)
                    valueText += "상대목표가";
                else if (a_Type == 5)
                    valueText += "교차가";

                if (a_Type == 0 && m_EnableBase == false)
                    return;
                if (a_Type == 1 && m_EnableMonthLow == false)
                    return;
                if (a_Type == 2 && m_EnableMonthHigh == false)
                    return;
                if (a_Type == 3 && m_EnableJoint == false)
                    return;
                if (a_Type == 4 && m_EnableTarget == false)
                    return;
                if (a_Type == 5 && m_EnableCross == false)
                    return;

                Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                FontStyle.Regular);

                System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                // Set the TextRenderingHint property.
                graphics.TextRenderingHint =
                    System.Drawing.Text.TextRenderingHint.AntiAlias;


                xMin = area.AxisX.Minimum;
                xMax = area.AxisX.Maximum;
                YMin = area.AxisY2.Minimum;
                YMax = area.AxisY2.Maximum;
                YValue = a_Val;

                if (YValue > YMax || YValue < YMin)
                    return;
                if (YValue == double.NaN)
                    return;

                string curValue = String.Format("{0:F2}", YValue);

                valueText += " : " + curValue;

                // Convert X and Y values to screen position
                float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, YValue);
                float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, area.AxisY2.Maximum);
                float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);


                // Set Maximum points
                PointF[] points = new PointF[3];
                points[0].X = pixelXMin;
                points[0].Y = pixelY;

                points[1].X = pixelXMax;
                points[1].Y = pixelY;

                points[2].X = pixelXMin;
                points[2].Y = pixelMaxY;


                // Convert relative coordinates to absolute coordinates.
                points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                if (sideCode == "2")
                {
                    graphics.DrawLine(new Pen(Color.Red, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Red, points[0].X, points[0].Y);
                }
                else
                {
                    graphics.DrawLine(new Pen(Color.Blue, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Blue, points[0].X, points[0].Y);
                }

            }
        }

        private void FutOptChartCtrl_PostPaint(object sender, System.Windows.Forms.DataVisualization.Charting.ChartPaintEventArgs e)
        {
            if (m_DataFilled == true)
                DrawSignal(e);
            if (m_DataFilled == true && m_EnableOpConstPrice == true)
                DrawConstPrice(e);
            if (m_DataFilled == true)
                DrawCurVal(e);
            DrawSeriesName(e);
            if (m_DataFilled == true)
            {
                DrawDDEPrice(e);
                DrawCrossPrice(e);
            }
        }


        private bool m_EnableBase = true;
        private bool m_EnableMonthHigh = true;
        private bool m_EnableMonthLow = true;
        private bool m_EnablePreDayHigh = true;
        private bool m_EnablePreDayLow = true;
        private bool m_EnableOpConstPrice = false;
        private bool m_EnableJoint = true;
        private bool m_EnableTarget = true;
        private bool m_EnableCross = false;


        private void cbBase_CheckedChanged(object sender, EventArgs e)
        {
            if (cbBase.Checked)
                m_EnableBase = true;
            else
                m_EnableBase = false;
        }

        private void FutOptChartCtrl_Click(object sender, EventArgs e)
        {
            int i = 0;
            i = i + 1;
        }

        private void FutOptChartCtrl_CursorPositionChanging(object sender, CursorEventArgs e)
        {
            int i = 0;
            i = i + 1;
        }

        ToolTip tooltip = new ToolTip();
        Point prevPosition = new Point();

        private void FutOptChartCtrl_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Point pos = e.Location;
            var results = FutOptChartCtrl.HitTest(pos.X, pos.Y, false,
                                         ChartElementType.PlottingArea);
            foreach (var result in results)
            {
                if (result.ChartElementType == ChartElementType.PlottingArea)
                {
                    var xVal = result.ChartArea.AxisX.PixelPositionToValue(pos.X);
                    var yVal = result.ChartArea.AxisY.PixelPositionToValue(pos.Y);

                    tooltip.Show("X=" + xVal + ", Y=" + yVal,
                                 this.FutOptChartCtrl, e.Location.X, e.Location.Y - 15);
                }
            }

        }

        private void FutOptChartCtrl_MouseMove(object sender, MouseEventArgs e)
        {
            Point pos = e.Location;
            if (!prevPosition.IsEmpty && pos == prevPosition)
                return;
            tooltip.RemoveAll();
            prevPosition = pos;
            var results = FutOptChartCtrl.HitTest(pos.X, pos.Y, false,
                                         ChartElementType.PlottingArea);
            foreach (var result in results)
            {
                if (result.ChartElementType == ChartElementType.PlottingArea)
                {
                    var xVal = result.ChartArea.AxisX.PixelPositionToValue(pos.X);
                    var yVal = result.ChartArea.AxisY.PixelPositionToValue(pos.Y);

                    tooltip.Show(result.ChartArea.Name + ":" + "X=" + xVal.ToString("F2") + ", Y=" + yVal.ToString("F2"),
                                 this.FutOptChartCtrl, e.Location.X, e.Location.Y - 15);
                }
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            /*
            EasyTrader.Option.DDEDayDataCollection preDayCol = m_OpDataSet.FindPrevDDEDayDataCol(m_OpDataSet.DownLoadManager.CurDay);
            m_OpDataSet.DownLoadManager.SetDay(preDayCol.Date);
            m_OpDataSet.DownLoadManager.FillMonthData(preDayCol);
            m_OpDataSet.SetCurDayState(preDayCol);
            m_OpDataSet.SetPreDayState(preDayCol);
            m_OpDataSet.ClearChartDataArray();
            m_OpDataSet.DownLoadManager.ChartTryCount = 0;
             */
            // 먼저 날짜를 바꿔준다.
            int preDay = m_OpDataSet.DownLoader.FindPreOpenDay(Convert.ToInt32(m_OpDataSet.DownLoader.CurDay));
            if (preDay == 0)
                return;
            m_OpDataSet.DownLoader.CurDay = preDay;
            m_CallCode = m_OpDataSet.DownLoader.GetCallAtm(m_OpDataSet.DownLoader.CurDay);
            tbCurDay.Text = m_OpDataSet.DownLoader.CurDay.ToString();
            m_OpDataSet.DownLoader.MakeOptChartCodeList();
            GlobalVar.StateMessage = "데이터를 다운로드 중입니다. 잠시만 기다려 주세요.";
            // 등가를 찾는다.
            // 등가에 따라서 테이블 목록을 다시 만든다.
            // 중심 인덱스를 바꿔준다.
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            /*
            string callCode = m_OpDataSet.ChartCodeArray[1];
            string putCode = m_OpDataSet.ChartCodeArray[4];
            m_OpDataSet.DownLoadManager.FillChartCodeList(callCode, putCode);
             */
            int listCount = m_OpDataSet.OptChartTableList.Count;
            int halfCount = (int)(listCount / 2.0);
            int endIndex = m_CenterIndex + 1 + m_IndexRange;
            if (endIndex < halfCount)
            {
                m_CallCode = m_OpDataSet.OptChartTableList[m_CenterIndex + 1].TableName;
            }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            //string callCode = m_OpDataSet.ChartCodeArray[3];
            //string putCode = m_OpDataSet.ChartCodeArray[6];
            //m_OpDataSet.DownLoadManager.FillChartCodeList(callCode, putCode);
            int listCount = m_OpDataSet.OptChartTableList.Count;
            int startIndex = m_CenterIndex - 1 - m_IndexRange;
            if (startIndex >= 0)
            {
                m_CallCode = m_OpDataSet.OptChartTableList[m_CenterIndex - 1].TableName;
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            /*
            EasyTrader.Option.DDEDayDataCollection nextDayCol = m_OpDataSet.FindNextDDEDayDataCol(m_OpDataSet.DownLoadManager.CurDay);
            m_OpDataSet.DownLoadManager.SetDay(nextDayCol.Date);
            m_OpDataSet.DownLoadManager.FillMonthData(nextDayCol);
            m_OpDataSet.SetCurDayState(nextDayCol);
            m_OpDataSet.SetPreDayState(nextDayCol);
            m_OpDataSet.ClearChartDataArray();
            m_OpDataSet.DownLoadManager.ChartTryCount = 0;
             */

            // 먼저 날짜를 바꿔준다.
            int nextDay = m_OpDataSet.DownLoader.FindNextOpenDay(Convert.ToInt32(m_OpDataSet.DownLoader.CurDay));
            if (nextDay == 0)
                return;
            m_OpDataSet.DownLoader.CurDay = nextDay;
            m_CallCode = m_OpDataSet.DownLoader.GetCallAtm(m_OpDataSet.DownLoader.CurDay);
            //tbCurDay.Text = m_OpDataSet.DownLoader.CurDay.ToString();
            m_OpDataSet.DownLoader.MakeOptChartCodeList();
            GlobalVar.StateMessage = "데이터를 다운로드 중입니다. 잠시만 기다려 주세요.";
        }

        private void cbOpConst_CheckedChanged(object sender, EventArgs e)
        {
            ;
        }

        private void cbMonthLow_CheckedChanged(object sender, EventArgs e)
        {
            if (cbMonthLow.Checked)
                m_EnableMonthLow = true;
            else
                m_EnableMonthLow = false;
        }

        private void cbPreLow_CheckedChanged(object sender, EventArgs e)
        {
            ;
        }

        private void cbMonthHigh_CheckedChanged(object sender, EventArgs e)
        {
            if (cbMonthHigh.Checked)
                m_EnableMonthHigh = true;
            else
                m_EnableMonthHigh = false;
        }

        private void cbPreHigh_CheckedChanged(object sender, EventArgs e)
        {
            ;
        }

        private void rbMonth_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMonth.Checked)
            {
                m_OpDataSet.DownLoader.OptChartUnit = 'M';
                m_OpDataSet.DownLoader.OptChartMethod = '2';
            }
        }

        private void rbDay_CheckedChanged(object sender, EventArgs e)
        {
            if (rbDay.Checked)
            {
                m_OpDataSet.DownLoader.OptChartUnit = 'D';
                m_OpDataSet.DownLoader.OptChartMethod = '2';
            }
        }

        private void rbMin_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMin.Checked)
            {
                m_OpDataSet.DownLoader.OptChartUnit = 'm';
                m_OpDataSet.DownLoader.OptChartMethod = '1';
            }
        }

        private void comboCycle_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboCycle.SelectedIndex == -1)
                return;

            m_OpDataSet.DownLoader.OptChartCycle = Convert.ToInt16(comboCycle.SelectedItem.ToString());
        }

        private int m_ShowType = 2; // 0 : 모두 , 1 : 선물만, 2 : 옵션만, 3 : 콜만, 4 : 풋만

        private void comboShowType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboShowType.SelectedIndex == -1)
                return;
            m_ShowType = comboShowType.SelectedIndex;
        }

        private void cbJoint_CheckedChanged(object sender, EventArgs e)
        {
            if (cbJoint.Checked)
                m_EnableJoint = true;
            else
                m_EnableJoint = false;
        }

        private void cbTarget_CheckedChanged(object sender, EventArgs e)
        {
            if (cbTarget.Checked)
                m_EnableTarget = true;
            else
                m_EnableTarget = false;
        }


    }
}
